  /*
  * MinIO Cloud Storage (C) 2018 MinIO, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

  import React from "react";
  import { createStyles, makeStyles, withStyles, Theme } from '@material-ui/core/styles';
  import ReactEcharts from 'echarts-for-react';
  import Alert from '@material-ui/lab/Alert';
  import Collapse from '@material-ui/core/Collapse';
  import api from "../../../common/api";
  import { ChartUrl, beforeNowtimeBySec } from "./types";

  const styles = (theme: Theme) =>
  createStyles({
    nodeTitle: {
      position: "relative",
      height:"170px"
    },
    alert: {
      position: "absolute",
      width: "100%",
      textAlign: "center",
      zIndex: 1000, 
      top: 35
    },
    alertPop: {
      margin: "0 auto",
      width: "130px"
    },
});

interface ChartState {
  classes: any;
  // option: object,
  // open: false,
  inputNode: string,
}
export class NodeDiskFree extends React.Component<ChartState, any> {
  constructor(props:any){
    super(props);
    this.state = {
      loading: false,
      msg:"",
      dataWarn:"",
      oldNode:"",
      newNode:"",
      open: false
    };
  };
  setOpen(a:boolean){
    this.setState({
      open: a
    })
  }
  getChart(type:any) {
    // 硬盘剩余空间百分比
    let url = ChartUrl+"((sum(node_filesystem_free_bytes{fstype='xfs'})by(instance))/(sum(node_filesystem_size_bytes{fstype='xfs'})by(instance)))*100&start="+Date.parse(beforeNowtimeBySec(30)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeBySec(0)).toString().substring(0,10)+"&step=1";
    api
      .invoke("GET", url)
      .then((res) => {
        var rootData = res.data.result;
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            var x = rootData[i].values.length-1
            if(rootData[i].metric.instance== type ){
              this.setState({
                xdata: parseFloat(rootData[i].values[x][1]).toFixed(2)
              });
              break;
            }else{
              this.setState({
                dataWarn: "暂无数据",
                xdata: ""
              });
              this.setOpen(true);
            }
          }
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      .catch(err => {
        this.setState({
          dataWarn: "暂无数据",
          loading: false 
        })
        this.setOpen(true);
      });
  }
  componentDidUpdate(prevProps:any): void {
    if(prevProps.inputNode !== this.state.oldNode){
        this.getChart(this.state.oldNode);
        var timer = setInterval(() => {
          let url = window.location.href
          if(url.indexOf("/nodeexporter") != -1){
            this.getChart(this.state.oldNode);
          }else{
            clearInterval(timer)
          }
        }, 25000)
    }
  }
  static getDerivedStateFromProps(nextProps:any, prevState:any) {
    // 当传入的type发生变化的时候，更新state
    if (nextProps.inputNode !== prevState.oldNode) {
      return {
        oldNode: nextProps.inputNode
      }
    }
    // 否则，对于state不进行任何操作
    return null;
  }
  getOption= () => ({
      series: [{
        type: 'gauge',
        center: ['50%', '70%'],
        radius: '95%',
        endAngle: -15,
        startAngle:195,
        axisLine: {            // 坐标轴线
          lineStyle: {       // 属性lineStyle控制线条样式
            width: 10,
            color:[[0.7, '#5793f3'], [0.9, '#F4A024'], [1, '#c23531']]
          }
        },
        axisTick: {            // 坐标轴小标记
          length: 0
        },
        axisLabel: {            // 坐标轴小标记
          show:false
        },
        splitLine: {           // 分隔线
          length: 0
        },
        pointer: {
          width: 5
        },
        detail: {formatter: this.state.xdata+'%'},
        data: [{value: this.state.xdata}]
      }]
  });
  render() {
    const { classes } = this.props;
    return (
      <div className={classes.nodeTitle}>
        {!this.state.xdata ? (
        <div className={classes.alert}>
          <Collapse in={this.state.open} className={classes.alertPop}>
            <Alert severity="error" style={{padding: "0 16px"}}>
              {this.state.dataWarn}
            </Alert>
          </Collapse>
        </div>
        ):(
          <ReactEcharts
          ref="chart"
          option={this.getOption()}
          style={{height: '170px', width: '100%', paddingTop: 5}} />
        )}
      </div>
    );
  }
};
export default withStyles(styles)(NodeDiskFree)